package com.example.administrator.newxlmedical;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.administrator.baseproject.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import adapters.ComboSetAdapter;
import beans.ComboBean;
import beans.ItemEntity;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import constants.HandlerConstant;
import dialogs.ComboSetDeleteDialog;
import interfaces.MyItemClickListener;
import netframe.GetRetrofit;
import netframe.NetAddress;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utils.ComboSetSortUtils;
import utils.DefaultFuzzySearchRule;
import utils.FuzzySearchUtils;
import utils.ScreenUtils;
import utils.ToastUtil;
import utils.ViewUtil;

public class ComboSetActivity extends BaseActivity implements ComboSetAdapter.ComboSetListener {

    @BindView(R.id.iv_combo_set_home)
    ImageView ivHome;
    @BindView(R.id.et_combo_set_name)
    EditText etName;
    @BindView(R.id.tv_combo_set_search)
    TextView tvSearch;
    @BindView(R.id.tv_combo_set_add)
    TextView tvAdd;
    @BindView(R.id.tv_combo_set_goods)
    TextView tvGoods;
    @BindView(R.id.iv_warn_set_goods_sort)
    ImageView ivGoodsSort;
    @BindView(R.id.rl_combo_set_goods_sort)
    RelativeLayout rlGoodsSort;
    @BindView(R.id.tv_combo_set_category)
    TextView tvCategory;
    @BindView(R.id.iv_combo_set_category_sort)
    ImageView ivCategorySort;
    @BindView(R.id.rl_combo_set_category_sort)
    RelativeLayout rlCategorySort;
    @BindView(R.id.tv_combo_set_date)
    TextView tvDate;
    @BindView(R.id.iv_combo_set_date_sort)
    ImageView ivDateSort;
    @BindView(R.id.rl_combo_set_date_sort)
    RelativeLayout rlDateSort;
    @BindView(R.id.rv_combo_set_activity)
    RecyclerView recyleview;
    @BindView(R.id.fl_combo_set_empty)
    FrameLayout flEmpty;
    private ComboSetAdapter adapter;
    private List<ComboBean.DataBean> list = new ArrayList<>();
    private List<ComboBean.DataBean> allList = new ArrayList<>();
    private List<ComboBean.DataBean> sortList = new ArrayList<>();
    private ArrayList<String> comboNameList = new ArrayList<>();
    private DefaultFuzzySearchRule mIFuzzySearchRule;
    private FuzzySearchFilter fuzzySearchFilter;
    private boolean isSortGoods, isSortSpecification, isSortSupplier;
    private int sortGoods, sortSpecification, sortSupplier;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_combo_set);
        ButterKnife.bind(this);
        getData();
    }

    @Override
    public void initView() {
        super.initView();
        mIFuzzySearchRule = new DefaultFuzzySearchRule();
        fuzzySearchFilter = new FuzzySearchFilter();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyleview.setLayoutManager(layoutManager);
        adapter = new ComboSetAdapter(this, this,list);
        recyleview.setAdapter(adapter);
    }

    @Override
    protected void setListener() {
        super.setListener();

        adapter.setItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                ComboBean.DataBean dataBean = list.get(position);
                Intent intent = new Intent(ComboSetActivity.this, ComboInfoActivity.class);
                intent.putExtra("id",dataBean.getID());
                intent.putExtra("comboName",dataBean.getPackageName());
                startActivity(intent);
            }
        });

        etName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId== EditorInfo.IME_ACTION_SEARCH ||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)){
                    search();
                    return true;
                }

                return false;
            }
        });
    }

    private void getData() {
        hideEmptyView();
        showLoadingView(flEmpty);
        comboNameList.clear();
        list.clear();
        allList.clear();
        sortList.clear();
        comboNameList.clear();
        GetRetrofit.getInstance().getComboData(NetAddress.token, NetAddress.machineCode, "")
                .enqueue(new Callback<ComboBean>() {
                    @Override
                    public void onResponse(Call<ComboBean> call, Response<ComboBean> response) {
                        ComboBean body = response.body();
                        if (body != null && body.getData() != null && body.getData().size() != 0) {
                            list.addAll(body.getData());
                            allList.addAll(body.getData());
                            sortList.addAll(body.getData());
                            for (int i = 0; i < body.getData().size(); i++) {
                                comboNameList.add(body.getData().get(i).getPackageName());
                            }
                            ComboSetSortUtils.sortComboSetGoods(list, true);
                        } else {
                            showEmptyView(flEmpty);
                        }
                        adapter.notifyDataSetChanged();
                        hideLoadingView();

                    }

                    @Override
                    public void onFailure(Call<ComboBean> call, Throwable t) {
                        showEmptyView(flEmpty);
                        hideLoadingView();
                    }
                });
    }

    @OnClick({R.id.iv_combo_set_home, R.id.tv_combo_set_search, R.id.tv_combo_set_add, R.id.rl_combo_set_category_sort, R.id.rl_combo_set_date_sort,
            R.id.rl_combo_set_goods_sort})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_combo_set_home:
                finish();
                break;
            case R.id.tv_combo_set_search:
                search();
                break;
            case R.id.tv_combo_set_add:
                jump2ComboModifyAndAddActivity("添加",0,"");
                break;
            case R.id.rl_combo_set_goods_sort:
                sort(1);
                break;
            case R.id.rl_combo_set_category_sort:
                sort(2);
                break;
            case R.id.rl_combo_set_date_sort:
                sort(3);
                break;
        }
    }

    private void search() {
        hideEmptyView();
        sort(0);
        ScreenUtils.closeKeybord(etName, ComboSetActivity.this);
        String comboName = etName.getText().toString();
        if (!TextUtils.isEmpty(comboName)){
            fuzzySearchFilter.filter(comboName);
        }else {
            getData();
        }
    }

    @Override
    public void modify(int position) {
        ComboBean.DataBean dataBean = list.get(position);
        jump2ComboModifyAndAddActivity("修改",dataBean.getID(),dataBean.getPackageName());
    }

    @Override
    public void delete(final ComboBean.DataBean bean, final int position) {
        ComboSetDeleteDialog dialog = new ComboSetDeleteDialog(this, R.style.dialog, bean.getPackageName(), new ComboSetDeleteDialog.ComboSetDeleteInterface() {
            @Override
            public void sure() {
                GetRetrofit.getInstance().deleteCombo(NetAddress.token,NetAddress.machineCode,String.valueOf(bean.getID()))
                        .enqueue(new Callback<ComboBean>() {
                            @Override
                            public void onResponse(Call<ComboBean> call, Response<ComboBean> response) {
                                if (response.code() == 200 ){
                                    ToastUtil.showToast(ComboSetActivity.this,"删除成功");
                                    list.remove(position);
                                    sortList.clear();
                                    sortList.addAll(list);
                                    adapter.notifyDataSetChanged();
                                }else {
                                    ToastUtil.showToast(ComboSetActivity.this,"删除失败");
                                }
                            }

                            @Override
                            public void onFailure(Call<ComboBean> call, Throwable t) {
                                ToastUtil.showToast(ComboSetActivity.this,"删除失败");
                            }
                        });
            }
        });
        dialog.show();
    }


    private void jump2ComboModifyAndAddActivity(String type,int position,String comboName) {
        Intent intent = new Intent(ComboSetActivity.this, ComboModifyAndAddActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("id",position);
        intent.putExtra("comboName",comboName);
        intent.putStringArrayListExtra("comboNameList",comboNameList);
        startActivity(intent);
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what){
            case HandlerConstant.COMBO_SET_REFRESH:
                getData();
                break;

            case HandlerConstant.FUZZY_SEARCH :
                if (list.size() == 0){
                    showEmptyView(flEmpty);
                }
                adapter.notifyDataSetChanged();
                break;
        }
    }

    private class FuzzySearchFilter extends Filter {

        /**
         * 执行过滤操作,如果搜索的关键字为空，默认所有结果
         */

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<ItemEntity> dateList = FuzzySearchUtils.fillComboData(allList);
            FilterResults result = new FilterResults();
            List<ItemEntity> filterList = new ArrayList<>();
            for (ItemEntity item : dateList) {
                if (mIFuzzySearchRule.accept(constraint, item.getSourceKey(), item.getFuzzyKey())) {
                    filterList.add(item);
                }
            }
            result.values = filterList;
            result.count = filterList.size();
            return result;
        }

        /**
         * 得到过滤结果
         */
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            list.clear();
            sortList.clear();
            List<ItemEntity> mDataList = (List<ItemEntity>) results.values;
            if (mDataList != null && mDataList.size() != 0) {
                for (int i = 0; i < mDataList.size(); i++) {
                    ItemEntity itemEntity = mDataList.get(i);
                    list.add(itemEntity.getComboBean());
                    sortList.add(itemEntity.getComboBean());
                    Log.e(TAG, "publishResults: " +  itemEntity.getComboBean().getPackageName());
                }
            }
            sendEmptyMessage(HandlerConstant.FUZZY_SEARCH);
        }
    }

    private void sort(int type) {
        if (type == 1) { // 按物品名排序
            if (sortGoods != 2) {
                isSortGoods = !isSortGoods;
                sortGoods++;
                ComboSetSortUtils.sortComboSetGoods(list, isSortGoods);
            } else {
                clearSortDate();
            }
        } else {
            sortGoods = 0;
            isSortGoods = false;
        }

        if (type == 2) { // 按供应商排序
            if (sortSupplier != 2) {
                sortSupplier++;
                isSortSupplier = !isSortSupplier;
                ComboSetSortUtils.sortComboSetCategory(list, isSortSupplier);
            } else {
                clearSortDate();
            }
        } else {
            sortSupplier = 0;
            isSortSupplier = false;
        }

        if (type == 3) {
            if (sortSpecification != 2) {
                sortSpecification++;
                isSortSpecification = !isSortSpecification;
                ComboSetSortUtils.sortComboSetDate(list, isSortSpecification);
            } else {
                clearSortDate();
            }
        } else {
            sortSpecification = 0;
            isSortSpecification = false;
        }

        ViewUtil.setSortColor(this, tvGoods, ivGoodsSort, sortGoods);
        ViewUtil.setSortColor(this, tvCategory, ivCategorySort, sortSupplier);
        ViewUtil.setSortColor(this, tvDate, ivDateSort, sortSpecification);

        adapter.notifyDataSetChanged();
    }

    private void clearSortDate() {
        list.clear();
        list.addAll(sortList);
        sortGoods = 0;
        sortSupplier = 0;
        sortSpecification = 0;
    }
}
